<script setup>
import { usePriceSummaryStore } from '@/stores/index.js'
import _ from 'lodash'
import { ref, defineExpose, defineProps, nextTick, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { storeToRefs } from 'pinia'

const priceSummaryStore = usePriceSummaryStore()
const { fields, fieldsObject } = storeToRefs(priceSummaryStore)
// const fieldsForForm = ref(priceSummaryStore.fieldsObject)
const fieldsLeftSet = computed(() => {
  const usedValues = new Set(Object.values(fieldsObject.value))
  // console.log(usedValues)
  return props.headerArr.filter(field => !usedValues.has(field))
})

let rules = {}
// console.log(fields)
for (const [key, value] of fields.value.entries()) {
  rules[key] = {
    required: true,
    message: key + '不能为空',
    trigger: 'blur'
  }
}
// console.log('fieldsForForm', fieldsForForm)

const dialogFormVisible = ref(false)
const fieldsFormRef = ref(null)
let callback = null
let callbackArgs = []
defineExpose({
  // open: (headerArr, fieldsNotMatched, cb, ...cbArgs) => {
  open: (cb, ...cbArgs) => {
    // console.log('fields', fields)
    // console.log(headerArr)
    // console.log('fieldsNotMatched', props.fieldsNotMatched)
    let values = []
    for (const value of fields.value.values()) {
      values.push(value)
    }
    // fieldsLeftSet.value = new Set(_.difference(headerArr, values))
    // console.log('fieldsLeftSet', fieldsLeftSet)
    // console.log('props.fieldsNotMatched', props.fieldsNotMatched)
    // console.log('props.fieldsNotMatched.length', props.fieldsNotMatched.length)
    if (props.fieldsNotMatched) {
      // console.log('fields', fields)
      // console.log('fieldsForForm', fieldsForForm)
      if (!_.isEmpty(fieldsObject.value)) {
        props.fieldsNotMatched.forEach(key => {
          fieldsObject.value[key] = ''
        })
      }
    }

    callback = cb
    callbackArgs = cbArgs

    // console.log('fieldsFormRef', fieldsFormRef)
    nextTick(() => {
      // console.log('fieldsFormRef.value', fieldsFormRef.value)
      fieldsFormRef.value?.validate((valid, fields) => {
        // console.log('valid', valid)
        // console.log('fields', fields)
        if (!valid) {
          ElMessage.error('存在与默认模板字段不匹配的字段')
        }
      })
    })
    dialogFormVisible.value = true
  }
})

const formLabelWidth = '140px'

const updateFields = () => {
  fieldsFormRef.value.validate((valid, fields) => {
    if (!valid) {
      ElMessage.error('存在与默认模板字段不匹配的字段')
    } else {
      priceSummaryStore.setFields(fieldsObject.value)
      dialogFormVisible.value = false
      nextTick(() => {
        if (callback) {
          callback(...callbackArgs)
        }
        ElMessage.success('字段映射完成, 请点击"生成"按钮生成核价单')
      })
    }
  })
}

const props = defineProps({
  fieldsNotMatched: {
    type: Object,
    default: () => ({})
  },
  headerArr: {
    type: Object,
    default: () => ({})
  }
})
</script>

<template>
  <el-dialog v-model="dialogFormVisible" title="字段名映射配置" width="500">
    <el-text style="color: red;display: block;margin-bottom: 10px">以下为生成核价单时所模板所需必要的字段,
      请配置对应的列名：
    </el-text>
    <el-form :model="fieldsObject" ref="fieldsFormRef" :rules="rules">
      <el-form-item :prop="key" :label="key" :label-width="formLabelWidth"
                    v-for="(value, key) in fieldsObject">
        <el-select v-model="fieldsObject[key]" :placeholder="`请选择模板中使用到${key} 映射的列名`" filterable
                   :disabled="key === 'contract'"
                   style="width: 240px">
          <el-option
            v-for="item in [...Array.from(fieldsLeftSet)]"
            :key="item"
            :label="item"
            :value="item"
            filterable
          />
        </el-select>
      </el-form-item>
    </el-form>
    <el-button size="large" class="subBtn" @click="updateFields">
      确定
    </el-button>
  </el-dialog>
</template>

<style scoped>
.subBtn {
  width: 100%;
  background: #409eff;
  color: #fff;
  border: none;
}
</style>
